package com.example.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.enums.ExamListType;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.RedisService;
import com.example.friend.domain.exam.Exam;
import com.example.friend.domain.exam.ExamQuestion;
import com.example.friend.domain.exam.dto.ExamQueryDTO;
import com.example.friend.domain.exam.vo.ExamVO;
import com.example.friend.domain.user.UserExam;
import com.example.friend.mapper.exam.ExamMapper;
import com.example.friend.mapper.exam.ExamQuestionMapper;
import com.example.friend.mapper.user.UserExamMapper;
import com.example.security.exception.ServiceException;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.Log_$logger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/3/9 15:38
 */

@Component
public class ExamCacheManager {

    @Resource
    private ExamMapper examMapper;

    @Resource
    private UserExamMapper userExamMapper;

    @Resource
    private ExamQuestionMapper examQuestionMapper;
//
//    @Resource
//    private UserExamMapper userExamMapper;

    @Resource
    private RedisService redisService;

    //获取redis中列表的元素个数
    public Long getListSize(Integer examListType,Long userId) {
        String examListKey = getExamListKey(examListType,userId);
        return redisService.getListSize(examListKey);
    }

    //从redis中获取每个竞赛下的题目的数量
    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }

//
//    public Long getRankListSize(Long examId) {
//        return redisService.getListSize(getExamRankListKey(examId));
//    }

    //从redis中获取数据
    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO,Long userId) {

        //计算下标
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1

        //判断要获取未完赛还是历史竞赛的list的数据 并获取到
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);

        //根据查到的id来获取竞赛基本信息
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        //如果从redis中获取数据失败了
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO,userId); //从数据库中获取数据
            //刷新缓存
            refreshCache(examQueryDTO.getType(),userId);
        }
        return examVOList;
    }

//    public List<ExamRankVO> getExamRankList(ExamRankDTO examRankDTO) {
//        int start = (examRankDTO.getPageNum() - 1) * examRankDTO.getPageSize();
//        int end = start + examRankDTO.getPageSize() - 1; //下标需要 -1
//        return redisService.getCacheListByRange(getExamRankListKey(examRankDTO.getExamId()), start, end, ExamRankVO.class);
//    }

    //获取redis中当前用户的所有已报名的竞赛
    public List<Long> getAllUserExamList(Long userId) {
        String examListKey = CacheConstants.USER_EXAM_LIST + userId;
        List<Long> userExamIdList = redisService.getCacheListByRange(examListKey, 0, -1, Long.class);
        if (CollectionUtil.isNotEmpty(userExamIdList)) {
            return userExamIdList;
        }
        //如果redis中不存在，那么从数据库中获取
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId));
        if (CollectionUtil.isEmpty(userExamList)) {
            return null;
        }
        //刷新缓存
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
        //stream流获取
        return userExamList.stream().map(UserExam::getExamId).collect(Collectors.toList());
    }

    //往redis中存储用户报名的竞赛
    public void addUserExamCache(Long userId, Long examId) {
        //拼接redis中的key
        String userExamListKey = getUserExamListKey(userId);
        //判断redis中是否已经报名过，如果已经报名过，那么就不能往里面存
        List<Long> list = redisService.getCacheListByRange(userExamListKey, 0, -1, Long.class);
        if (CollectionUtil.isNotEmpty(list) && list.contains(examId)){
            System.out.println("redis中已经存在此条报名信息，建议重新刷新缓存");
            return;
        }
        //放到redis中，头插
        redisService.leftPushForList(userExamListKey, examId);
    }

    //从redis中找到当前竞赛下的第一个题目
    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId), 0, Long.class);
    }

    //从redis中找到前一个题目id
    public Long preQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index - 1, Long.class);
    }

    //从redis中找到下一个题目id
    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        long lastIndex = getExamQuestionListSize(examId) - 1;
        if (index == lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index + 1, Long.class);
    }

    //刷新缓存逻辑  未完赛竞赛 历史竞赛 用户报名竞赛
    public void refreshCache(Integer examListType,Long userId) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, 1)
                    .orderByDesc(Exam::getStartTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, 1)
                    .orderByDesc(Exam::getStartTime));
        }else if (ExamListType.USER_EXAM_LIST.getValue().equals(examListType)){
            //查询用户报名竞赛
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            //使用hutu工具类，将examVO的list复制到exam的list
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
//        System.out.println("数据库中的数据："+examList.size());
//        System.out.println(examList);
        //判断数据库里是否有数据
        if (CollectionUtil.isEmpty(examList)) {
            redisService.deleteObject(getExamListKey(examListType,userId));
            return;
        }

        //将拿到的数据放到redis中
        Map<String, Exam> examMap = new HashMap<>();  //exam:detail:examId - exam详情
        List<Long> examIdList = new ArrayList<>();  //用于刷新未完赛和历史竞赛的数据
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        //批量的将竞赛详情存到redis中 exam:detail:examId:竞赛详情
        redisService.multiSet(examMap);  //刷新详情缓存
        //删除未完赛或历史竞赛列表或用户报名竞赛的列表  然后重新存储
        redisService.deleteObject(getExamListKey(examListType,userId));
        redisService.rightPushAll(getExamListKey(examListType,userId), examIdList);      //刷新列表缓存
    }

    //刷新每个exam中题目的信息到redis中
    public void refreshExamQuestionCache(Long examId) {
        //从数据库中查询当前竞赛包含的题目id
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId, examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        if (CollectionUtil.isEmpty(examQuestionList)) {
            return;
        }
        //将examQuestion的列表中每个对象的值放到一个新的list中
        List<Long> examQuestionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        //存入redis中
        redisService.rightPushAll(getExamQuestionListKey(examId), examQuestionIdList);
        //节省 redis缓存资源，redis的键设置为竞赛结束后的一天
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getExamQuestionListKey(examId), seconds, TimeUnit.SECONDS);
    }

//    public void refreshExamRankCache(Long examId) {
//        List<ExamRankVO> examRankVOList = userExamMapper.selectExamRankList(examId);
//        if (CollectionUtil.isEmpty(examRankVOList)) {
//            return;
//        }
//        redisService.rightPushAll(getExamRankListKey(examId), examRankVOList);
//    }


    //从数据库里面获取竞赛数据
    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO,Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if (ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())) {
            //查询我的竞赛列表
            return userExamMapper.selectUserExamList(userId);
        }
        //查询未完赛和历史竞赛的竞赛列表
        return examMapper.selectExamList(examQueryDTO);
    }



    //根据拿到的id，然后获取竞赛的基本信息
    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        //根据key获取redis中的竞赛基本信息
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);//移除redis中null的数据
        //判断获取的竞赛详情和竞赛列表中的数量是否一致
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    //拼接当前访问的是未完赛列表还是历史竞赛列表的key
    private String getExamListKey(Integer examListType,Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }

    //拼接redis中的key的内容
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    //拼接redis中用户报名的竞赛列表的key  每个用户一个列表
    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }




    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

//
//    private String getExamRankListKey(Long examId) {
//        return CacheConstants.EXAM_RANK_LIST + examId;
//    }
}
